<?php

if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {

    require_once './admin/includes/db.php';

    $mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
    $mysqli->set_charset("utf8");

    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL with MySQLI: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    $nom = $_POST['nom'];
    $prenom = $_POST['prenom'];
    $mail = $_POST['mail'];
    
    $sql = "select mail from and_participant where mail='".$mail."'";
    $result = $mysqli->query($sql);
    
    $row = $result->fetch_assoc();
    
    
    if($row['mail'] == $mail) {
        echo '<img src="images/echec.png" width="200px" class="aligncenter"/><p class="erreur"><b>Vous êtes déjà inscrit<br />Prière de nous contacter en cas d\'erreur</b></p>';
        $mysqli->close();
        exit();
    }
    

    $tel = $_POST['tel'];
    $institution = $_POST['institution'];
    $labo = $_POST['labo'];
    $fonction = $_POST['fonction'];
    $se = $_POST['se'];
    $adresse = addslashes($_POST['adresse']);
    $premier = $_POST['premier'];
    $payement = $_POST['payement'];
    $accompagne = $_POST['accompagne'];

    $nb = 0;
    if ($accompagne == "Oui") {
        $nb = $_POST['nb'];
    }

    $sql0 = "INSERT INTO and_participant ( nom, prenom, mail, tel, institution, labo, fonction, se, adresse, premier, payement, accompagne, nb_accompagnants) 
        VALUES ('" . $nom . "', '" . $prenom . "', '" . $mail . "', '" . $tel . "', '" . $institution . "', '" . $labo . "', '" . $fonction . "', '" . $se . "', '" . $adresse . "', '" . $premier . "', '" . $payement . "', '" . $accompagne . "', '" . $nb . "')";

    
    $mysqli->query($sql0);

    if ($mysqli->affected_rows > 0) {

        if ($accompagne == "Oui") {



            $id = $mysqli->insert_id;



            for ($index = 1; $index <= $nb; $index++) {

                $noma = "nb" . $index;
                $datea = "date" . $index;
                $sql1 = "insert into and_accompagnants (nom_prenom, date_naissance, id_participant) values ('" . $_POST[$noma] . "', '" . $_POST[$datea] . "', " . $id . ")";
                $mysqli->query($sql1);
                
            }
        }
    }


    $mysqli->close();

    echo '<img src="images/succes.png" width="200px" class="aligncenter" /><p class ="ok"><b>Inscription effectuée avec succès</b></p>';

    exit();
} else {

    $mysqli->close();

    echo '<img src="images/echec.png" width="200px" class="aligncenter" /><p class="erreur"><b>Echec de l\'inscription</b></p>';

    exit();
}



exit();
?>
 